package com.xiaoh.dormitoryrepairreportbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoh.dormitoryrepairreportbackend.common.ErrorCode;
import com.xiaoh.dormitoryrepairreportbackend.exception.BusinessException;
import com.xiaoh.dormitoryrepairreportbackend.mapper.NotificationMapper;
import com.xiaoh.dormitoryrepairreportbackend.model.entity.Notification;
import com.xiaoh.dormitoryrepairreportbackend.service.NotificationService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 通知表 服务实现类
 */
@Service
public class NotificationServiceImpl extends ServiceImpl<NotificationMapper, Notification>
        implements NotificationService {

    @Override
    public boolean createNotification(Long recipientId, String title, String content, String relatedType, Long relatedId) {
        Notification notification = new Notification();
        notification.setRecipientId(recipientId);
        notification.setTitle(title);
        notification.setContent(content);
        notification.setRelatedType(relatedType);
        notification.setRelatedId(relatedId);
        notification.setIsRead(0);
        
        return this.save(notification);
    }

    @Override
    public boolean markAsRead(Long notificationId, Long userId) {
        Notification notification = this.getById(notificationId);
        if (notification == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "通知不存在");
        }
        
        if (!notification.getRecipientId().equals(userId)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作此通知");
        }
        
        notification.setIsRead(1);
        return this.updateById(notification);
    }

    @Override
    public boolean markAllAsRead(Long userId) {
        UpdateWrapper<Notification> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("recipient_id", userId);
        updateWrapper.eq("is_read", 0);
        updateWrapper.set("is_read", 1);
        
        return this.update(updateWrapper);
    }

    @Override
    public long getUnreadCount(Long userId) {
        QueryWrapper<Notification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("recipient_id", userId);
        queryWrapper.eq("is_read", 0);
        
        return this.count(queryWrapper);
    }
}
